/**
 * Copyright (c) 2011 Paul Wagner
 */
package com.pew.tasktimer.domain;

import java.util.ArrayList;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

import org.apache.log4j.*;

/**
 * @author Elwin
 * Created: Mar 30, 2011
 * Purpose: A storage wrapper for the XML documents.
 * Provides a facade to get at the rest of the domain objects.
 *
 */
@XmlRootElement (name = "TaskTimer")
public class TaskTimerPackage {

	static Logger cLogger = Logger.getLogger(TaskTimerPackage.class);
	
	@XmlElementWrapper(name = "tasks")
	@XmlElement(name = "task")
	private ArrayList<Task> cTaskArray = new ArrayList<Task>();
	
	public void addTask(Task myTask)
	{
		if (cLogger.isDebugEnabled()) {
			cLogger.debug("Adding task: " + myTask.toString());
		}
		cTaskArray.add(myTask);
	}
	
	public Task[] getTasks() {
		Task lTask[] = new Task[cTaskArray.size()];
		return cTaskArray.toArray(lTask);
	}
	
	public Task getLatestRunningTask(){
		Task lTask = null;
		long lTime = -1;
		for (Task t : cTaskArray)
		{
			if(t.isRunning())
			{
				if (t.getClStartTime() > lTime)
				{
					lTime = t.getClStartTime();
					lTask = t;
				}
			}
		}
		
		return lTask;
	}
	
	/**
	 * Used to clean-up when only one task is allowed to be running at a time.
	 */
	public void stopRunningTasks() {
		for (Task t : cTaskArray)
		{
			if(t.isRunning())
			{
				t.stopTimer();
				t.setPotentialyBad(true);
				t.setcStrPotentialyBad("Stopped when cleaning up open data.");
			}
		}
	}
	
	/**
	 * Used to fix older Task objects without a Unique ID.
	 */
	public void setUniqueIDs() {
		for(Task t : cTaskArray) {
			if(t.getUniqueID() < 1) {
				t.setUniqueID();
			}
		}
	}
	
	public boolean storeThisTask(Task myTask){
		
		if (cLogger.isDebugEnabled()) {
			cLogger.debug("Attempting to store a task.  Checking if it already exists.");
		}
		
		boolean isNewTask = true;
		if(myTask == null){
			cLogger.warn("A NULL object was passed into this method.  Returning false");
			return false;
		}
		
		for (Task t : cTaskArray){
			if(t.getUniqueID() == myTask.getUniqueID()) {
				if (cLogger.isDebugEnabled()) {
					cLogger.debug("Found task already existed.");
				}
				isNewTask = false;
				t = myTask;
				break;
			}
		}
		
		if (cLogger.isDebugEnabled()) {
			cLogger.debug("Return task is new? " + isNewTask);
		}
		return isNewTask;
	}
	
	public String toString()
	{
		StringBuffer lStrBuff = new StringBuffer("Contents of TaskTimerPackage: ");
		
		for(Task t : cTaskArray)
		{
			lStrBuff.append(t.toString() + ";");
		}
		
		return lStrBuff.toString();
	}
	
	
}
